<template>
  <el-table
    :header-cell-style="{ 'text-align': 'center' }"
    :data="downloadQueue"
    @row-contextmenu="rightClick"
    style="width: 100%"
    height="100%"
  >
    <el-table-column width="38">
      <template slot-scope="scope">
        <i class="icon" :class="getSuffix(scope.row.filename)"></i>
      </template>
    </el-table-column>
    <el-table-column label="文件名" show-overflow-tooltip align="left">
      <template slot-scope="scope">
        <span>{{ scope.row.filename }}</span>
      </template>
    </el-table-column>
    <el-table-column label="下载进度" align="center">
      <template slot-scope="scope">
        <el-progress
          :percentage="
            scope.row.fileSize !== -1
              ? parseInt(
                  ((scope.row.downloaded / scope.row.fileSize) * 100).toFixed(0)
                )
              : 0
          "
        >
        </el-progress>
      </template>
    </el-table-column>
    <el-table-column label="文件大小" align="center">
      <template slot-scope="scope">
        <span>
          {{
            scope.row.fileSize === -1
              ? "未知"
              : (scope.row.fileSize / Math.pow(1024, 2)).toFixed(2) + "M"
          }}
        </span>
      </template>
    </el-table-column>
  </el-table>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import store from "@/store";
export default {
  name: "Download",
  computed: {
    ...mapGetters(["downloadQueue"])
  },
  data() {
    return { types: ["zip", "mp3", "mp4"] };
  },
  mounted() {
    const p = this;
    this.$bus.$on("startQueue", function() {
      if (p.$options.name === p.$router.currentRoute.name) {
        this.$bus.$emit("startDownloadQueue");
      }
    });

    this.$bus.$on("pauseQueue", function() {
      if (p.$options.name === p.$router.currentRoute.name) {
        this.$emit("stopDownloadQueue");
      }
    });

    this.$bus.$on("clearQueue", function() {
      if (p.$options.name === p.$router.currentRoute.name) {
        store.commit("CLEAR_DOWNLOAD_QUEUE");
      }
    });
  },
  destroyed() {
    this.$bus.$off(["startQueue", "pauseQueue", "clearQueue"]);
  },
  methods: {
    ...mapActions(["deleteDownloadQueueElement"]),
    rightClick(row, column, event) {
      this.$contextmenu({
        items: [
          {
            label: "删除",
            onClick: () => {
              this.deleteDownloadQueueElement(row);
            }
          }
        ],
        event,
        zIndex: 3,
        minWidth: 140
      });
    },
    getSuffix(filename) {
      const suffix = filename
        .split(".")
        .slice(-1)
        .pop();
      return this.types.indexOf(suffix) > 0 ? suffix : "misc";
    }
  }
};
</script>
